package com.duojuhe.coremodule.chat.im.service.impl;

import com.duojuhe.common.annotation.KeyLock;
import com.duojuhe.common.constant.DataScopeConstants;
import com.duojuhe.common.enums.IdResourceEnum;
import com.duojuhe.common.file.service.FileUploadHandler;
import com.duojuhe.common.utils.file.UploadFileBean;
import com.duojuhe.coremodule.chat.im.entity.ChatEmoticonItem;
import com.duojuhe.coremodule.chat.im.entity.ChatTalkRecord;
import com.duojuhe.coremodule.chat.im.entity.ChatTalkRecordFile;
import com.duojuhe.coremodule.chat.im.mapper.ChatEmoticonItemMapper;
import com.duojuhe.coremodule.chat.im.mapper.ChatGroupUserMapper;
import com.duojuhe.coremodule.chat.im.mapper.ChatTalkRecordFileMapper;
import com.duojuhe.coremodule.chat.im.mapper.ChatTalkRecordMapper;
import com.duojuhe.coremodule.chat.im.pojo.dto.emoticon.item.*;
import com.duojuhe.coremodule.chat.im.service.ChatEmoticonItemService;
import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.bean.DataScopeFilterBean;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.config.FileUploadConfig;
import com.duojuhe.common.enums.chat.ImChatEnum;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.encryption.md5.MD5Util;
import com.duojuhe.common.utils.file.UploadFileUtil;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ChatEmoticonItemServiceImpl extends BaseService implements ChatEmoticonItemService {
    @Resource
    private FileUploadConfig fileUploadConfig;
    @Resource
    private FileUploadHandler fileUploadHandler;
    @Resource
    private ChatTalkRecordMapper chatTalkRecordMapper;
    @Resource
    private ChatGroupUserMapper chatGroupUserMapper;
    @Resource
    private ChatTalkRecordFileMapper chatTalkRecordFileMapper;
    @Resource
    private ChatEmoticonItemMapper chatEmoticonItemMapper;
    /**
     *【查询用户表情包服务接口】分页查询用户表情包服务接口
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.SELF_DATA)
    @Override
    public ServiceResult<PageResult<List<QueryChatUserEmoticonItemPageRes>>> queryChatUserEmoticonItemPageResList(QueryChatUserEmoticonItemPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "createTime asc, itemId asc");
        List<ChatEmoticonItemRes> list = chatEmoticonItemMapper.queryChatUserEmoticonItemPageResList(req);
        return PageHelperUtil.returnServiceResult(req,list);
    }

    /**
     *【查询用户表情包服务接口】查询用户表情
     * @param dataScope
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.SELF_DATA)
    @Override
    public ServiceResult<QueryMyChatEmoticonItemRes> queryMyChatEmoticonItemRes(DataScopeFilterBean dataScope) {
        PageHelperUtil.defaultOrderBy("createTime asc, itemId asc");
        List<ChatEmoticonItemRes> list = chatEmoticonItemMapper.queryMyChatEmoticonItemRes(dataScope);
        QueryMyChatEmoticonItemRes res = new QueryMyChatEmoticonItemRes();
        res.setCollectEmoticonList(list);
        res.setSystemEmoticonList(new ArrayList<>());
        return ServiceResult.ok(res);
    }

    /**
     *【查询系统表情包服务接口】分页查询系统表情包服务接口
     * @param req
     * @return
     */
    @Override
    public ServiceResult<PageResult<List<QueryChatSystemEmoticonItemPageRes>>> queryChatSystemEmoticonItemPageResList(QueryChatSystemEmoticonItemPageReq req) {
        return PageHelperUtil.returnServiceResult(req,new ArrayList<>());
    }


    /**
     * 收藏表情包服务接口
     * @param req
     * @return
     */
    @KeyLock(lockKeyParts = "recordId")
    @Override
    public ServiceResult collectChatEmoticonItem(CollectChatEmoticonItemReq req) {
        ChatTalkRecord chatTalkRecord = chatTalkRecordMapper.selectByPrimaryKey(req.getRecordId());
        //是否标识
        Integer yes = ImChatEnum.IM_YES_NO.YES.getKey();
        if (chatTalkRecord==null || yes.equals(chatTalkRecord.getIsRevoke())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //不是文件类型禁止该操作
        if (!ImChatEnum.TalkMessageType.FILE_MESSAGE.getKey().equals(chatTalkRecord.getMsgType())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //用户id
        String userId = userTokenInfoVo.getUserId();
        //判断是否是私聊
        if (ImChatEnum.TalkType.PRIVATE_CHAT.getKey().equals(chatTalkRecord.getTalkType())){
            if (!userId.equals(chatTalkRecord.getReceiverId())&&!userId.equals(chatTalkRecord.getUserId())){
                return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
            }
        }else {
            //主键ID 当前用户id和接收id的MD5值
            String id = MD5Util.getMD532(userId+chatTalkRecord.getReceiverId());
            if (chatGroupUserMapper.selectByPrimaryKey(id)==null){
                return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
            }
        }
        ChatTalkRecordFile recordFile = chatTalkRecordFileMapper.selectByPrimaryKey(chatTalkRecord.getRecordId());
        if (recordFile==null || !ImChatEnum.FileType.FILE_IMAGE.getKey().equals(recordFile.getFileType())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        if (chatEmoticonItemMapper.selectByPrimaryKey(recordFile.getFileId())!=null){
            return ServiceResult.fail("已收藏过该图片，请勿重复收藏!");
        }
        //添加到收藏
        Date nowDate = new Date();
        ChatEmoticonItem emoticonItem = new ChatEmoticonItem();
        emoticonItem.setItemId(recordFile.getFileId());
        emoticonItem.setCategoryId(recordFile.getFileId());
        emoticonItem.setCreateTime(nowDate);
        emoticonItem.setEmoticonUrl(recordFile.getFileUrl());
        emoticonItem.setFileSuffix(recordFile.getFileSuffix());
        emoticonItem.setUpdateTime(nowDate);
        emoticonItem.setFileSize(recordFile.getFileSize());
        emoticonItem.setFileType(recordFile.getFileType());
        emoticonItem.setOriginalName(recordFile.getOriginalName());
        emoticonItem.setRemark("收藏表情");
        emoticonItem.setIsCollect(yes);
        emoticonItem.setCreateUserId(userId);
        chatEmoticonItemMapper.insertSelective(emoticonItem);
        return ServiceResult.ok(ErrorCodes.SUCCESS);
    }


    /**
     * 保存用户表情包服务接口 系统表情包保存成自己的表情包
     * @param req
     * @return
     */
    @Override
    public ServiceResult saveChatEmoticonItem(SaveChatEmoticonItemReq req) {
        return ServiceResult.fail("功能正在开发中...");
    }


    /**
     *【自定义表情】新增自定义表情
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult<String> uploadDiyChatEmoticonItem(MultipartFile file) {
        if (file==null||file.isEmpty()){
            return ServiceResult.fail(ErrorCodes.UPLOAD_FILE_NOT_FOUND);
        }
        // 判断文件大小
        long fileSize = file.getSize();
        long maxImageSize = fileUploadConfig.getMaxSize(fileUploadConfig.getMaxImageSize());
        if (fileSize > maxImageSize) {
            return ServiceResult.fail(ErrorCodes.UPLOAD_FILE_TOO_LARGE);
        }
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前登录人id
        String userId = userTokenInfoVo.getUserId();
        //用户编号
        String userNumber = userTokenInfoVo.getUserNumber();
        //用户表情目录dir
        String chatEmoticonDir = File.separator+"chatEmoticon"+File.separator+userNumber;
        //文件根目录
        String rootPath = fileUploadConfig.getRootPath()+chatEmoticonDir;
        //文件前缀
        String imageUrlPrefix = fileUploadConfig.getFileUrlPrefix()+chatEmoticonDir;
        //附件上传前缀域名
        String filePrefixDomain = fileUploadConfig.getFilePrefixDomain();
        //允许图片文件类型
        String[] allowFiles = fileUploadConfig.getImageAllowFiles();
        //构建对象
        UploadFileBean uploadFileBean = UploadFileUtil.writeSingleImageToDisk(file,allowFiles,filePrefixDomain, rootPath, imageUrlPrefix);
        //请求路径
        String fileAbsolutePath = uploadFileBean.getFileAbsolutePath();
        if (StringUtils.isBlank(fileAbsolutePath)) {
            return ServiceResult.fail(ErrorCodes.UPLOAD_FILE_FORMAT_ERROR);
        }
        //主键
        String id = UUIDUtils.getUUID32();
        //保存文件到文件库
        //关联id来源
        String relationIdSource = IdResourceEnum.IdResource.chat_emoticon_item.getKey();
        fileUploadHandler.addRelationNewFileUpload(id,relationIdSource,uploadFileBean,userTokenInfoVo);
        //添加到收藏
        Date nowDate = new Date();
        //文件后缀
        String fileSuffix = UploadFileUtil.getFileSuffix(file);
        //文件名称
        String originalName = file.getOriginalFilename();
        ChatEmoticonItem emoticonItem = new ChatEmoticonItem();
        emoticonItem.setItemId(id);
        emoticonItem.setCategoryId(id);
        emoticonItem.setCreateTime(nowDate);
        emoticonItem.setEmoticonUrl(fileAbsolutePath);
        emoticonItem.setFileSuffix(fileSuffix);
        emoticonItem.setUpdateTime(nowDate);
        emoticonItem.setRemark(originalName);
        emoticonItem.setIsCollect(ImChatEnum.IM_YES_NO.YES.getKey());
        emoticonItem.setCreateUserId(userId);
        emoticonItem.setFileSize(fileSize);
        emoticonItem.setFileType(ImChatEnum.FileType.FILE_IMAGE.getKey());
        emoticonItem.setOriginalName(originalName);

        chatEmoticonItemMapper.insertSelective(emoticonItem);
        ChatEmoticonItemRes itemRes = new ChatEmoticonItemRes();
        itemRes.setItemId(id);
        itemRes.setEmoticonUrl(fileAbsolutePath);
        itemRes.setIsCollect(ImChatEnum.IM_YES_NO.YES.getKey());
        return ServiceResult.ok(itemRes);
    }
}
